import * as THREE from 'three'
import { stats } from '../stats'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

function createCourse27 (dom: HTMLElement) {
  const scene = new THREE.Scene()

  const camera = new THREE.PerspectiveCamera(75, dom.offsetWidth / dom.offsetHeight, 0.01, 1000)
  camera.position.set(20, 20, 20)

  const render = new THREE.WebGLRenderer()
  render.setSize(dom.offsetWidth, dom.offsetHeight)
  render.shadowMap.enabled = true

  dom.appendChild(render.domElement)

  const axes = new THREE.AxesHelper(100)
  scene.add(axes)

  camera.position.x = -20
  camera.position.y = 20
  camera.position.z = 30
  camera.lookAt(scene.position)
  scene.add(camera)

  const controls = new OrbitControls(camera, render.domElement)
  controls.update()

  createSprites()

  function getTexture () {
    const texture = new THREE.TextureLoader().load('https://dongli-three.oss-cn-shanghai.aliyuncs.com/sprite-sheet.png')
    return texture
  }

  function createSprites () {
    for (let x = -30; x < 30; x++) {
      for (let y = -20; y < 20; y++) {
        for (let z = 0; z < 5; z++) {
          const spriteMaterial = new THREE.SpriteMaterial({
            opacity: 0.5,
            transparent: false,
            color: 0xffffff,
            map: getTexture()
          })

          spriteMaterial.map!.offset = new THREE.Vector2(0.2 * z, 0)
          spriteMaterial.map!.repeat = new THREE.Vector2(1 / 5, 1)
          spriteMaterial.depthTest = false

          const sprite = new THREE.Sprite(spriteMaterial)
          sprite.position.set(x * 4, y * 4, z * 100)
          scene.add(sprite)
        }
      }
    }
  }

  render.setAnimationLoop(anmation)

  function anmation () {
    stats.update()
    render.render(scene, camera)
  }

  return { camera, scene, render }
}

export {
  createCourse27
}
